package com.cooper.util;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

import org.apache.commons.io.FileUtils;

public class GenerateCodeUtils {

	private String[] colnames; // 列名数组
	private String[] colTypes; // 列名类型数组
	private int[] colSizes; // 列名大小数组
	private boolean f_util = false; // 是否需要导入包java.util.*
	private boolean f_sql = false; // 是否需要导入包java.sql.*

	// 数据库连接
	private static final String URL = "jdbc:mysql://121.40.208.2:3306/mixuan";
	private static final String NAME = "root";
	private static final String PASS = "toor";
	private static final String DRIVER = "com.mysql.jdbc.Driver";
	private Connection conn;

	public GenerateCodeUtils() {

		try {
			Class.forName(DRIVER);
		} catch (ClassNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

	}

	public void GenerateDoCode(String packagePath, String tableName) {
		PreparedStatement pstmt = null;
		String strsql = "select * from " + tableName;
		try {
			try {
				conn = DriverManager.getConnection(URL, NAME, PASS);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			pstmt = conn.prepareStatement(strsql);
			ResultSetMetaData rsmd = pstmt.getMetaData();
			int size = rsmd.getColumnCount(); // 共有多少列
			colnames = new String[size];
			colTypes = new String[size];
			colSizes = new int[size];
			for (int i = 0; i < rsmd.getColumnCount(); i++) {
				colnames[i] = this.getCamelStr(rsmd.getColumnName(i + 1));
				colTypes[i] = rsmd.getColumnTypeName(i + 1);

				colSizes[i] = rsmd.getColumnDisplaySize(i + 1);
				if (this.isExcludeCol(colnames[i])) {
					continue;
				}
				if (colTypes[i].equalsIgnoreCase("datetime")

				|| colTypes[i].equalsIgnoreCase("date")) {

					f_util = true;
				}
				if (colTypes[i].equalsIgnoreCase("image")
						|| colTypes[i].equalsIgnoreCase("text")
						|| colTypes[i].equalsIgnoreCase("timestamp")) {
					f_sql = true;
				}
			}
			try {
				String content = parseForDo(colnames, colTypes, colSizes,
						packagePath, tableName);
				String path = System.getProperty("user.dir")
						+ "/src/main/java/"
						+ packagePath.replaceAll("\\.", "/");
				File file = new File(path);
				if (!file.exists()) {
					file.mkdirs();
				}
				String resPath = path + "/" + initcap(tableName) + ".java";
				System.out.println("resPath=" + resPath);
				FileUtils.writeStringToFile(new File(resPath), content);
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				pstmt.close();
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

	public void GenerateVoCode(String packagePath, String tableName) {
		PreparedStatement pstmt = null;
		String strsql = "select * from " + tableName;
		try {
			try {
				conn = DriverManager.getConnection(URL, NAME, PASS);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			pstmt = conn.prepareStatement(strsql);
			ResultSetMetaData rsmd = pstmt.getMetaData();
			int size = rsmd.getColumnCount(); // 共有多少列
			colnames = new String[size];
			colTypes = new String[size];
			colSizes = new int[size];
			for (int i = 0; i < rsmd.getColumnCount(); i++) {
				colnames[i] = this.getCamelStr(rsmd.getColumnName(i + 1));
				colTypes[i] = rsmd.getColumnTypeName(i + 1);

				colSizes[i] = rsmd.getColumnDisplaySize(i + 1);
				if (this.isExcludeCol(colnames[i])) {
					continue;
				}
				if (colTypes[i].equalsIgnoreCase("datetime")

				|| colTypes[i].equalsIgnoreCase("date")) {

					f_util = true;
				}
				if (colTypes[i].equalsIgnoreCase("image")
						|| colTypes[i].equalsIgnoreCase("text")
						|| colTypes[i].equalsIgnoreCase("timestamp")) {
					f_sql = true;
				}
			}
			try {
				String content = parseForVo(colnames, colTypes, colSizes,
						packagePath, tableName);
				String path = System.getProperty("user.dir")
						+ "/src/main/java/"
						+ packagePath.replaceAll("\\.", "/");
				File file = new File(path);
				if (!file.exists()) {
					file.mkdirs();
				}
				String resPath = path + "/" + initcap(tableName) + "Vo"
						+ ".java";
				System.out.println("resPath=" + resPath);
				FileUtils.writeStringToFile(new File(resPath), content);
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				pstmt.close();
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

	/**
	 * 解析处理(生成实体类主体代码)
	 */
	private String parseForDo(String[] colNames, String[] colTypes,
			int[] colSizes, String packagePath, String tableName) {
		StringBuffer sb = new StringBuffer();
		sb.append("package " + packagePath + ";\r\n\r\n");
		if (f_util) {
			sb.append("import java.util.Date;\r\n");
		}
		sb.append("import com.mixuan.domain.BaseDo;\r\n");
		if (f_sql) {
			sb.append("import java.sql.*;\r\n\r\n\r\n");
		}
		sb.append("public class " + initcap(tableName) + " extends BaseDo"
				+ "{\r\n\r\n");
		processAllAttrs(sb);
		sb.append("\r\n");
		processAllMethod(sb);
		sb.append("}\r\n");
		System.out.println(sb.toString());
		return sb.toString();

	}

	/**
	 * 解析处理(生成实体类主体代码)
	 */
	private String parseForVo(String[] colNames, String[] colTypes,
			int[] colSizes, String packagePath, String tableName) {
		StringBuffer sb = new StringBuffer();
		sb.append("package " + packagePath + ";\r\n\r\n");
		if (f_util) {
			sb.append("import java.util.Date;\r\n");
		}
		if (f_sql) {
			sb.append("import java.sql.*;\r\n\r\n\r\n");
		}
		sb.append("public class " + initcap(tableName) + "Vo"
				+ " extends BaseVo" + "{\r\n\r\n");
		processAllAttrs(sb);
		sb.append("\r\n");
		processAllMethod4Vo(sb);
		sb.append("}\r\n");
		System.out.println(sb.toString());
		return sb.toString();

	}

	/**
	 * 生成所有的方法
	 * 
	 * @param sb
	 */
	private void processAllMethod4Vo(StringBuffer sb) {
		for (int i = 0; i < colnames.length; i++) {
			if (this.isExcludeCol(colnames[i])) {
				continue;
			}
			sb.append("\tpublic void set" + initcap(colnames[i]) + "("
					+ sqlType2JavaType(colTypes[i]) + " " + colnames[i]
					+ "){\r\n");
			sb.append("\t\tchangeSupport.firePropertyChange(\"" + colnames[i]
					+ "\"," + "this." + colnames[i] + "," + colnames[i]
					+ ");\r\n");
			sb.append("\t\tthis." + colnames[i] + "=" + colnames[i] + ";\r\n");
			sb.append("\t}\r\n\r\n");

			sb.append("\tpublic " + sqlType2JavaType(colTypes[i]) + " get"
					+ initcap(colnames[i]) + "(){\r\n");
			sb.append("\t\treturn " + colnames[i] + ";\r\n");
			sb.append("\t}\r\n\r\n");
		}
	}

	/**
	 * 生成所有的方法
	 * 
	 * @param sb
	 */
	private void processAllMethod(StringBuffer sb) {
		for (int i = 0; i < colnames.length; i++) {
			if (this.isExcludeCol(colnames[i])) {
				continue;
			}
			sb.append("\tpublic void set" + initcap(colnames[i]) + "("
					+ sqlType2JavaType(colTypes[i]) + " " + colnames[i]
					+ "){\r\n");
			sb.append("\t\tthis." + colnames[i] + "=" + colnames[i] + ";\r\n");
			sb.append("\t}\r\n\r\n");

			sb.append("\tpublic " + sqlType2JavaType(colTypes[i]) + " get"
					+ initcap(colnames[i]) + "(){\r\n");
			sb.append("\t\treturn " + colnames[i] + ";\r\n");
			sb.append("\t}\r\n\r\n");
		}
	}

	private boolean isExcludeCol(String columName) {
		boolean isExclude = false;
		if ("id".equalsIgnoreCase(columName)) {
			isExclude = true;
		} else if ("id".equalsIgnoreCase(columName)) {
			isExclude = true;
		} else if ("name".equalsIgnoreCase(columName)) {
			isExclude = true;
		} else if ("comments".equalsIgnoreCase(columName)) {
			isExclude = true;
		} else if ("modifier".equalsIgnoreCase(columName)) {
			isExclude = true;
		} else if ("creator".equalsIgnoreCase(columName)) {
			isExclude = true;
		} else if ("deleted".equalsIgnoreCase(columName)) {
			isExclude = true;
		} else if ("gmtCreate".equalsIgnoreCase(columName)) {
			isExclude = true;
		} else if ("gmtModified".equalsIgnoreCase(columName)) {
			isExclude = true;
		}
		return isExclude;
	}

	/**
	 * 解析输出属性
	 * 
	 * @return
	 */
	private void processAllAttrs(StringBuffer sb) {
		for (int i = 0; i < colnames.length; i++) {
			if (this.isExcludeCol(colnames[i])) {
				continue;
			}
			sb.append("\tprivate " + sqlType2JavaType(colTypes[i]) + " "
					+ colnames[i] + ";\r\n");
		}
	}

	/**
	 * 把输入字符串的首字母改成大写
	 * 
	 * @param str
	 * @return
	 */
	private String initcap(String str) {
		char[] ch = str.toCharArray();
		if (ch[0] >= 'a' && ch[0] <= 'z') {
			ch[0] = (char) (ch[0] - 32);
		}
		return this.getCamelStr(new String(ch));
	}

	// 例：user_name --> userName
	private String getCamelStr(String s) {
		while (s.indexOf("_") > 0) {
			int index = s.indexOf("_");
			// System.out.println(s.substring(index+1, index+2).toUpperCase());
			s = s.substring(0, index)
					+ s.substring(index + 1, index + 2).toUpperCase()
					+ s.substring(index + 2);
		}
		return s;
	}

	private String sqlType2JavaType(String sqlType) {
		if (sqlType.equalsIgnoreCase("bit")) {
			return "Boolean";
		} else if (sqlType.equalsIgnoreCase("tinyint")) {
			return "Byte";
		} else if (sqlType.equalsIgnoreCase("smallint")) {
			return "Short";
		} else if (sqlType.equalsIgnoreCase("int")
				|| sqlType.equalsIgnoreCase("integer")) {
			return "Integer";
		} else if (sqlType.equalsIgnoreCase("bigint")) {
			return "Long";
		} else if (sqlType.equalsIgnoreCase("float")) {
			return "Float";
		} else if (sqlType.equalsIgnoreCase("decimal")
				|| sqlType.equalsIgnoreCase("numeric")
				|| sqlType.equalsIgnoreCase("real")) {
			return "Double";
		} else if (sqlType.equalsIgnoreCase("money")
				|| sqlType.equalsIgnoreCase("smallmoney")) {
			return "Double";
		} else if (sqlType.equalsIgnoreCase("varchar")
				|| sqlType.equalsIgnoreCase("char")
				|| sqlType.equalsIgnoreCase("nvarchar")
				|| sqlType.equalsIgnoreCase("nchar")
				|| sqlType.equalsIgnoreCase("longtext")) {
			return "String";
		} else if (sqlType.equalsIgnoreCase("datetime")
				|| sqlType.equalsIgnoreCase("date")) {
			return "Date";
		}

		else if (sqlType.equalsIgnoreCase("image")) {
			return "Blob";
		} else if (sqlType.equalsIgnoreCase("text")) {
			return "Clob";
		} else if (sqlType.equalsIgnoreCase("timestamp")) {
			return "Timestamp";
		}
		return null;
	}

	public static void main(String[] args) {
		String voPackagePath = "com.mixuan.vo";
		String tableName = "sys_org_info";
		GenerateCodeUtils generateCodeUtils = new GenerateCodeUtils();
		generateCodeUtils.GenerateVoCode(voPackagePath, tableName);
		// String doPackagePath = "com.mixuan.entity";
		//
		// generateCodeUtils.GenerateDoCode(doPackagePath,tableName);

	}

}